/*
 Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
 Original sources are available at www.latestbit.com

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

 ManagedConnection.cpp. Created on: 10.09.2009 17:24:13
 */

#include "smartobjects/network/ManagedConnection.hpp"
#include "smartobjects/network/ConnectionHandler.hpp"
#include "smartobjects/network/IManagedConnectionListener.hpp"
#include "smartobjects/network/IManagedStreamListener.hpp"

namespace smartobjects {

ManagedConnection::ManagedConnection() :
		m_poEndpointLocation(NULL),
		m_poEndpointCoordinator(NULL),
		m_bConnectionStatus(false),
		m_poCoordinatorContext(NULL) {
}

ManagedConnection::~ManagedConnection() {
	setCoordinatorContext(NULL);

	boost::recursive_mutex::scoped_lock oLock(m_mxEndpointLocation);
	releaseAndClear(m_poEndpointCoordinator);
	releaseAndClear(m_poEndpointLocation);
}


bool ManagedConnection::isOpen()  {
	return m_bConnectionStatus;
}

ConnectionHandler* ManagedConnection::getConnectionHandlerToSend()  {
	if(!m_poEndpointCoordinator)
		throw SmartBusSystemException("Unable to find any suitable connection (or coordinator) to send");
	return m_poEndpointCoordinator->getConnectionHandlerToSend(this);
}

void ManagedConnection::send(ConnectionHandler* poHandler, const ByteBuffer* poBuffer) {
	poHandler->getConnection()->send( poBuffer );
}

void ManagedConnection::addConnectionListener(class IManagedConnectionListener* poListener)  {
	boost::recursive_mutex::scoped_lock oLock ( m_mxConnectionListeners );
	if( !m_oPALConnectionListeners.isActivated() ) {
		m_aConnectionListeners.push_back(poListener);
	}
	else {
		m_oPALConnectionListeners.putListenerToAdd(poListener);
	}

}

void ManagedConnection::delConnectionListener(class IManagedConnectionListener* poListener)  {
	boost::recursive_mutex::scoped_lock oLock ( m_mxConnectionListeners );
	if( !m_oPALConnectionListeners.isActivated() ) {
		m_aConnectionListeners.remove(poListener);
	}
	else {
		m_oPALConnectionListeners.putListenerToRemove(poListener);
	}

}

void ManagedConnection::addStreamListener(class IManagedStreamListener* poListener)  {
	boost::recursive_mutex::scoped_lock oLock ( m_mxStreamListeners );
	if( !m_oPALStreamListeners.isActivated() ) {
		m_aStreamListeners.push_back(poListener);
	}
	else {
		m_oPALStreamListeners.putListenerToAdd(poListener);
	}

}

void ManagedConnection::delStreamListener(class IManagedStreamListener* poListener)  {
	boost::recursive_mutex::scoped_lock oLock ( m_mxStreamListeners );
	if( !m_oPALStreamListeners.isActivated() ) {
		m_aStreamListeners.remove(poListener);
	}
	else {
		m_oPALStreamListeners.putListenerToRemove(poListener);
	}
}

void ManagedConnection::processingPostActionConnectionListeners() {
	m_oPALConnectionListeners.deactivate();
	foreach( PostActionListenersContainer<IManagedConnectionListener>::PostActionQueueItem item, m_oPALConnectionListeners.getPostActionQueue()) {
		if(item.isActionToAdd()) {
			addConnectionListener( item.getListener() );
		}
		else
		if(item.isActionToRemove()) {
			delConnectionListener( item.getListener() );
		}
	}
	m_oPALConnectionListeners.reset();
}

void ManagedConnection::processingPostActionStreamListeners() {
	m_oPALStreamListeners.deactivate();
	foreach( PostActionListenersContainer<IManagedStreamListener>::PostActionQueueItem item, m_oPALStreamListeners.getPostActionQueue()) {
		if(item.isActionToAdd()) {
			addStreamListener( item.getListener() );
		}
		else
		if(item.isActionToRemove()) {
			delStreamListener( item.getListener() );
		}
	}
	m_oPALStreamListeners.reset();
}


void ManagedConnection::assignConnectionHandler(ConnectionHandler* poHandler)  {
	boost::recursive_mutex::scoped_lock oLock(m_mxHandlers);
	poHandler->setManagedConnection(this);
	m_aHandlers.insert(poHandler);
}

void ManagedConnection::unassignConnectionHandler(ConnectionHandler* poHandler)  {
	boost::recursive_mutex::scoped_lock oLock(m_mxHandlers);
	m_aHandlers.erase(poHandler);
	poHandler->resetManagedConnection();
}

void ManagedConnection::fireOnConnected()  {
	SafeForReleaseMethodLock oReleaseLock(this);
	boost::recursive_mutex::scoped_lock oLock(m_mxConnectionListeners);
	if(!m_bConnectionStatus) {
		m_bConnectionStatus = true;
		m_oPALConnectionListeners.activate();
		foreach(IManagedConnectionListener* poListener, m_aConnectionListeners) {
			poListener->onConnected(this);
		}
		processingPostActionConnectionListeners();
	}
}

void ManagedConnection::fireOnConnected(ConnectionHandler* poHandler)  {
	SafeForReleaseMethodLock oReleaseLock(this);
	boost::recursive_mutex::scoped_lock oLock(m_mxConnectionListeners);
	m_oPALConnectionListeners.activate();
	foreach(IManagedConnectionListener* poListener, m_aConnectionListeners) {
		poListener->onConnected( poHandler );
	}
	processingPostActionConnectionListeners();
}

void ManagedConnection::fireOnConnectionFailure( const std::string& sErrorMessage)  {
	SafeForReleaseMethodLock oReleaseLock(this);
	boost::recursive_mutex::scoped_lock oLock(m_mxConnectionListeners);
	m_bConnectionStatus = false;
	m_oPALConnectionListeners.activate();
	foreach(IManagedConnectionListener* poListener, m_aConnectionListeners) {
		poListener->onConnectionFailure( this, sErrorMessage );
	}
	processingPostActionConnectionListeners();
}

void ManagedConnection::fireOnConnectionFailure(ConnectionHandler* poHandler, const std::string& sErrorMessage)  {
	SafeForReleaseMethodLock oReleaseLock(this);
	boost::recursive_mutex::scoped_lock oLock(m_mxConnectionListeners);
	m_bConnectionStatus = false;
	m_oPALConnectionListeners.activate();
	foreach(IManagedConnectionListener* poListener, m_aConnectionListeners) {
		poListener->onConnectionFailure( poHandler, sErrorMessage );
	}
	processingPostActionConnectionListeners();
}

void ManagedConnection::fireOnDisconnected()  {
	SafeForReleaseMethodLock oReleaseLock(this);
	boost::recursive_mutex::scoped_lock oLock(m_mxConnectionListeners);
	if(m_bConnectionStatus) {
		m_bConnectionStatus = false;
		m_oPALConnectionListeners.activate();
		foreach(IManagedConnectionListener* poListener, m_aConnectionListeners) {
			poListener->onDisconnected(this);
		}
		processingPostActionConnectionListeners();
	}
}

void ManagedConnection::fireOnDisconnected(ConnectionHandler* poHandler)  {
	SafeForReleaseMethodLock oReleaseLock(this);
	boost::recursive_mutex::scoped_lock oLock(m_mxConnectionListeners);
	m_oPALConnectionListeners.activate();
	foreach(IManagedConnectionListener* poListener, m_aConnectionListeners) {
		poListener->onDisconnected( poHandler );
	}
	processingPostActionConnectionListeners();
}

void ManagedConnection::fireOnReceived(ConnectionHandler* poHandler, ByteBuffer* poBuffer)  {
	SafeForReleaseMethodLock oReleaseLock(this);
	boost::recursive_mutex::scoped_lock oLock(m_mxStreamListeners);
	m_oPALStreamListeners.activate();
	foreach(IManagedStreamListener* poListener, m_aStreamListeners) {
		poListener->onReceived( poHandler, poBuffer );
	}
	processingPostActionStreamListeners();
}

void ManagedConnection::fireOnReceiveError(ConnectionHandler* poHandler, const std::string& sErrorMessage)  {
	SafeForReleaseMethodLock oReleaseLock(this);
	boost::recursive_mutex::scoped_lock oLock(m_mxStreamListeners);
	m_oPALStreamListeners.activate();
	foreach(IManagedStreamListener* poListener, m_aStreamListeners) {
		poListener->onReceiveError( poHandler, sErrorMessage );
	}
	processingPostActionStreamListeners();

}

void ManagedConnection::fireOnWriteError(ConnectionHandler* poHandler, const std::string& sErrorMessage)  {
	SafeForReleaseMethodLock oReleaseLock(this);
	boost::recursive_mutex::scoped_lock oLock(m_mxStreamListeners);
	m_oPALStreamListeners.activate();
	foreach(IManagedStreamListener* poListener, m_aStreamListeners) {
		poListener->onWriteError( poHandler, sErrorMessage );
	}
	processingPostActionStreamListeners();

}

ICoordinatorContext* ManagedConnection::getCoordinatorContext()  {
	return m_poCoordinatorContext;
}

void ManagedConnection::setCoordinatorContext(ICoordinatorContext* poContext)  {
	setNewRefObject(m_poCoordinatorContext, poContext);
}

IEndpointLocation* ManagedConnection::getEndpointLocation() {
	boost::recursive_mutex::scoped_lock oLock( m_mxEndpointLocation );
	return m_poEndpointLocation;
}

}
